
require('plugins') -- .config/nvim/lua/plugins.lua

vim.opt.encoding = 'utf-8'
vim.opt.number = true
vim.opt.relativenumber = true
vim.opt.showcmd = true
vim.opt.hidden = true
vim.opt.showcmd = true
vim.opt.cmdheight = 2
vim.opt.mouse = 'a'
vim.opt.completeopt = { 'menu', 'menuone', 'noselect' }
vim.opt.cursorline = true
vim.opt.signcolumn = 'auto:3'
vim.opt.termguicolors = true
vim.opt.timeoutlen = 500
vim.cmd('au BufRead,BufNewFile *.p4 set filetype=p4')

-- local parser_config = require "nvim-treesitter.parsers".get_parser_configs()
-- 
-- parser_config.p4 = {
--   install_info = {
--     url = "https://github.com/victorxuyuwei/tree-sitter-p4", -- local path or git repo
--     files = {"src/parser.c"}
--   },
--   filetype = "p4"
-- }


require('aerial').setup({
  on_attach = function(bufnr)
    vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>a', '<cmd>AerialToggle!<CR>', {})
  end
})

require'nvim-treesitter.configs'.setup {
  -- ensure_installed = "maintained",
  context_commentstring = {
    enable = true,
    enable_autocmd = false,
  },
  highlight = {
    enable = true,
    disable = { "c", "rust" },
    additional_vim_regex_highlighting = false,
  },
  indent = {
    enable = true,
  },
}

require('Comment').setup {
  pre_hook = function(ctx)
    local U = require 'Comment.utils'

    local location = nil
    if ctx.ctype == U.ctype.block then
      location = require('ts_context_commentstring.utils').get_cursor_location()
    elseif ctx.cmotion == U.cmotion.v or ctx.cmotion == U.cmotion.V then
      location = require('ts_context_commentstring.utils').get_visual_start_location()
    end

    return require('ts_context_commentstring.internal').calculate_commentstring {
      key = ctx.ctype == U.ctype.line and '__default' or '__multiline',
      location = location,
    }
  end,
}

vim.opt.foldmethod = "expr"
vim.opt.foldexpr = "nvim_treesitter#foldexpr()"
vim.opt.foldlevel = 99

--- lsp config
local nvim_lsp = require('lspconfig')

local on_attach = function(client, bufnr)
  require("aerial").on_attach(client, bufnr)

  local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
  local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end

  -- Enable completion triggered by <c-x><c-o>
  buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')

  -- Mappings.
  local opts = { noremap=true, silent=true }

  -- See `:help vim.lsp.*` for documentation on any of the below functions
  buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
  buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
  buf_set_keymap('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
  buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
  buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
  buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
  buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
  buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
  buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
  buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
  buf_set_keymap('n', '<space>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
  buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
  buf_set_keymap('n', '<space>e', '<cmd>lua vim.diagnostic.open_float()<CR>', opts)
  buf_set_keymap('n', '[d', '<cmd>lua vim.diagnostic.goto_prev()<CR>', opts)
  buf_set_keymap('n', ']d', '<cmd>lua vim.diagnostic.goto_next()<CR>', opts)
  buf_set_keymap('n', '<space>q', '<cmd>lua vim.diagnostic.setloclist()<CR>', opts)
  buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)

end

--[[ local capabilities = vim.lsp.protocol.make_client_capabilities() ]]
--[[ capabilities.textDocument.completion.completionItem.snippetSupport = true ]]
--[[ capabilities.textDocument.completion.completionItem.resolveSupport = { ]]
--[[   properties = { ]]
--[[     'documentation', ]]
--[[     'detail', ]]
--[[     'additionalTextEdits', ]]
--[[   } ]]
--[[ } ]]

local cmp = require'cmp'
local luasnip = require 'luasnip'
-- luasnip.filetype_extend("javascript", { "javascriptreact" })
-- luasnip.filetype_extend("javascript", { "html" })

cmp.setup({
  snippet = {
    -- REQUIRED - you must specify a snippet engine
    expand = function(args)
      luasnip.lsp_expand(args.body)
    end,
  },
  mapping = {
    ['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }),
    ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }),
    ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }),
    ['<C-y>'] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping.
    ['<C-e>'] = cmp.mapping({
      i = cmp.mapping.abort(),
      c = cmp.mapping.close(),
    }),
    ['<CR>'] = cmp.mapping.confirm({ select = true }),
    ['<Tab>'] = cmp.mapping(function(fallback)
      if cmp.visible() then
        cmp.select_next_item()
      elseif luasnip.expand_or_jumpable() then
        luasnip.expand_or_jump()
      else
        fallback()
      end
    end, {'i', 's'}),
    ['<S-Tab>'] = cmp.mapping(function(fallback)
      if cmp.visible() then
        cmp.select_prev_item()
      elseif luasnip.jumpable(-1) then
        luasnip.jump(-1)
      else
        fallback()
      end
    end, {'i', 's'}),
  },
  sources = cmp.config.sources({
    { name = 'nvim_lsp' },
    { name = 'luasnip' },
  }, {
    { name = 'buffer' },
  })
})

-- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline('/', {
  sources = {
    { name = 'buffer' }
  }
})

-- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore).
cmp.setup.cmdline(':', {
  sources = cmp.config.sources({
    { name = 'path' }
  }, {
    { name = 'cmdline' }
  })
})

--[[ capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities) ]]
local capabilities = require('cmp_nvim_lsp').default_capabilities()

-- local servers = { 'clangd', 'pylsp' }
-- for _, lsp in ipairs(servers) do
--  nvim_lsp[lsp].setup({
--     on_attach = on_attach,
--     capabilities = capabilities,
--     debounce_text_changes = 150,
-- })
-- end
local lsp_settings = {
  clangd = {},
  pylsp = {
    pylsp = {
      configurationSources = {'flake8'},
      plugins = {
        flake8 = {enabled = true},
        pycodestyle = {enabled = false},
      }
    }
  },
  gopls = {},
  tsserver = {},
}

for lsp, settings in pairs(lsp_settings) do
  nvim_lsp[lsp].setup({
    on_attach = on_attach,
    capabilities = capabilities,
    debounce_text_changes = 150,
    settings = settings
  })
end

--- styles ---

-- require('github-theme').setup{
--   dark_float = true,
--   dark_sidebar = false,
--   -- theme_style = 'light',
--   -- transparent = true,
-- }

vim.g.tokyonight_style = "night"
vim.g.tokyonight_italic_functions = true
vim.g.tokyonight_colors = { hint = "orange", error = "#ff0000" }
vim.cmd[[colorscheme tokyonight]]

-- lualine should setup after github-theme
require('lualine').setup{
  options = {
    icons_enabled = true,
    -- theme = 'jellybeans',
    -- theme = 'auto',
    theme = 'tokyonight',
    section_separators = '',
    component_separators = '',
  },
}

require('bufferline').setup{
  options = {
    close_command = function(bufnum)
      require('bufdelete').bufdelete(bufnum, true)
    end,
    -- separator_style = "slant",
    offsets = {
      {
        filetype = "NvimTree",
        text = "File Explorer",
	      -- text = function()
        --    return vim.fn.getcwd()
        --  end,
        highlight = "Directory",
        text_align = "center"
      }
    }
  }
}

require("indent_blankline").setup {
  show_current_context = true,
  show_current_context_start = true,
  filetype_exclude = { "dashboard" },
}

vim.api.nvim_set_keymap('n', ']b', ':BufferLineCycleNext<CR>', {noremap = true, silent = true})
vim.api.nvim_set_keymap('n', '[b', ':BufferLineCyclePrev<CR>', {noremap = true, silent = true})

-- require'nvim-tree'
vim.api.nvim_set_keymap('n', '<C-n>', ':NvimTreeToggle<CR>', {noremap = true})
vim.api.nvim_set_keymap('n', '<leader>r', ':NvimTreeRefresh<CR>', {noremap = true})
vim.api.nvim_set_keymap('n', '<leader>n', ':NvimTreeFindFile<CR>', {noremap = true})
vim.api.nvim_create_autocmd("BufEnter", {
  nested = true,
  callback = function()
    if #vim.api.nvim_list_wins() == 1 and vim.api.nvim_buf_get_name(0):match("NvimTree_") ~= nil then
      vim.cmd "quit"
    end
  end
})


require('startup_config')
